#include <unistd.h>
#include <fcntl.h>

#include <iostream>


int main(){
    int fl = fcntl(0, F_GETFL);
    fcntl(0, F_SETFL, fl | O_NONBLOCK);
    // # define FNONBLOCK	O_NONBLOCK
    std::string prompt_msg = "Please Enter# \n";

    
    char buffer[1024];

    while(true){
        write(1, prompt_msg.c_str(), prompt_msg.size());
        int ret = read(0, buffer, sizeof(buffer));
        if(ret > 0)
        {
            buffer[ret] = '\0';
            std::cout << "echo# " << buffer << std::endl;
        }
        else if(ret == 0){
            std::cout << "read file end." << std::endl;
            break;
        }
        else{
            // #define	EWOULDBLOCK	EAGAIN	/* Operation would block */
            // #define	EAGAIN		11	/* Try again */
            if(errno == EAGAIN || errno == EWOULDBLOCK){
                std::cout << "Data package have not ready yet." << std::endl;
            }
            // 
            else{
                std::cout << "read error." << std::endl;
            }
        }
        sleep(1);
    }

    // while(true){
    //     int n = read(0,buffer,sizeof(buffer));

    //     printf("Nonblock read byte: %d\n", n);
    //     sleep(1);
    // }

    return 0;
}
